#!/bin/sh

set -e

# shellcheck disable=SC1091
[ -f /etc/sysconfig/alloy ] && . /etc/sysconfig/alloy
[ -z "$ALLOY_USER" ] && ALLOY_USER="alloy"
[ -z "$ALLOY_GROUP" ] && ALLOY_GROUP="alloy"

add_to_logging_groups() {
  # Add Alloy user to groups used for reading logs.
  if getent group adm > /dev/null 2>&1 ; then
      usermod -a -G adm "$ALLOY_USER"
  fi
  if getent group systemd-journal > /dev/null 2>&1 ; then
      usermod -a -G systemd-journal "$ALLOY_USER"
  fi
}

# Initial installation: $1 == 1
# Upgrade: $1 == 2, and configured to restart on upgrade
if [ "$1" -eq 1 ] ; then
    if ! getent group "$ALLOY_GROUP" > /dev/null 2>&1 ; then
        groupadd -r "$ALLOY_GROUP"
    fi
    if ! getent passwd "$ALLOY_USER" > /dev/null 2>&1 ; then
        useradd -r -m -g "$ALLOY_GROUP" -d /var/lib/alloy -s /sbin/nologin -c "alloy user" "$ALLOY_USER"
    fi

    add_to_logging_groups

    if [ ! -d /var/lib/alloy ]; then
      mkdir /var/lib/alloy
      chown "$ALLOY_USER":"$ALLOY_GROUP" /var/lib/alloy
      chmod 770 /var/lib/alloy
    fi

    if [ ! -d /var/lib/alloy/data ]; then
      mkdir /var/lib/alloy/data
      chown "$ALLOY_USER":"$ALLOY_GROUP" /var/lib/alloy/data
      chmod 770 /var/lib/alloy/data
    fi

    chown root:"$ALLOY_GROUP" /etc/alloy
    chmod 770 /etc/alloy

elif [ "$1" -ge 2 ] ; then
    add_to_logging_groups

    if [ "$RESTART_ON_UPGRADE" = "true" ]; then
        systemctl daemon-reload
        systemctl restart alloy
    fi
fi
